//
//  WNLocationManager.swift
//  WalkNovel
//
//  Created by Kevin on 2022/3/22.
//

import UIKit
import CoreLocation

class WNLocationManager: NSObject, CLLocationManagerDelegate {
    
    static let shared = WNLocationManager()
    
    var name = ""
    
    var country = ""
    
    var city = ""
        
    var location = CLLocation(latitude: 0, longitude: 0)
    
    var sucClosure: ReturnClosure?
    
    lazy var locationManager: CLLocationManager = {
        let loc = CLLocationManager()
        loc.delegate = self
        loc.requestAlwaysAuthorization()
        loc.requestWhenInUseAuthorization()
        loc.desiredAccuracy = kCLLocationAccuracyBest
        loc.distanceFilter = 10
        return loc
    }()
        
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        manager.stopUpdatingLocation()
        guard let newLocation = locations.last else { return }
        if newLocation.horizontalAccuracy < 0 { return }
        let geoCoder = CLGeocoder()
        location = newLocation
        geoCoder.reverseGeocodeLocation(newLocation) { [weak self] (placemarks: [CLPlacemark]?, error: Error?) in
            if error == nil {
                guard let placeMark = placemarks?.first else {
                    return
                }
                self?.country = placeMark.country ?? ""
                self?.city = placeMark.locality ?? ""
                self?.name = placeMark.name ?? ""
                WNThread.wn_runInMainThread {
                    self?.sucClosure?()
                }
            }else {
                
            }
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        manager.stopUpdatingLocation()
    }    
}

